package com.crm.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.dto.RoleDto;
import com.crm.dto.RoleExportDto;
import com.crm.entity.Course;
import com.crm.entity.Role;
import com.crm.result.PageResultTow;
import com.crm.result.Result;
import com.crm.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

//角色
@Slf4j
@RestController
@RequestMapping("/system")
public class RoleController {
@Resource
private RoleService roleService;

    @PostMapping("/role")
    public Result add(@RequestBody RoleDto roleDto){
        roleService.add(roleDto);
        return Result.success();
    }

    //分页查询
    @GetMapping("/role/list")
    public PageResultTow pageList( RoleDto roleDto){
        Page<Role> pageList = roleService.getPageList(roleDto);

         return PageResultTow.success(pageList.getRecords(), pageList.getTotal() );
    }

    //删除
    @DeleteMapping("/role/{ids}")
    public ResponseEntity<Boolean> batchDeleteRole(@PathVariable Long[] ids) {
        roleService.batchDeleteRole(ids);
        log.info("批量删除课程完成，共删除 {} 条记录", ids);
        return ResponseEntity.ok(true);
    }
    //修改
    @PutMapping("/role")
    public Result updateRole(@RequestBody Role role){
        roleService.updateRole(role);
        return Result.success();
    }

    //根据id查询
    @GetMapping("/role/{id}")
    public Result getById(@PathVariable Long id){
        Role role = roleService.getById(id);
        return Result.success(role);
    }


    //导出
    @GetMapping("/role/export")
    public void exportRoles(HttpServletResponse response) throws IOException {
        List<RoleExportDto> roleList = roleService.exportRoles();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=roles.xlsx");

        EasyExcel.write(response.getOutputStream(), RoleExportDto.class)
                .sheet("角色列表")
                .doWrite(roleList);
    }





}
